/*
 * Copyright ©2018 贾维程. All rights reserved.
 */

package com.rtmart.imageupload.controller.item;
import com.rtmart.imageupload.Tools.DateTools;
import com.rtmart.imageupload.Tools.FileTools;
import com.rtmart.imageupload.Tools.IntegerTools;
import com.rtmart.imageupload.entity.Item;
import com.rtmart.imageupload.repository.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/item/")
@PreAuthorize("hasAnyRole('ROLE_root','ROLE_admin')")
public class ItemImportController {
    @Autowired
    private ItemRepository itemRepository;

    @GetMapping("import")
    public String getImport(){
        return "item/import";
    }

    @PostMapping("import")
    @Transactional
    public String itemImport(@RequestParam("file") MultipartFile file, Model model){
        if (file.isEmpty()) {
            model.addAttribute("errorMessage","文件是空的！");
            return "item/import";
        }
        List<String[]> csvList;
        if (FileTools.isCsv(file)) {
            csvList = FileTools.csvRowList(file);
        } else {
            model.addAttribute("errorMessage","文件不是CSV文件！");
            return "item/import";
        }

        List<Item> itemList = new ArrayList<>();
        for(String[] itemArray : csvList){
            Item item = new Item();
            item.setNo(IntegerTools.stringToInteger(itemArray[0].trim()));
            item.setName(itemArray[1].trim());
            item.setLastDate(DateTools.stringToDate(itemArray[2].trim()));
            item.setState(IntegerTools.stringToInteger(itemArray[3].trim()));
            itemList.add(item);
        }
        itemRepository.deleteAllInBatch();
        /*List<Object[]> batch = new ArrayList<>();

        for (String[] itemArray : csvList) {
            Object[] values = new Object[] {
                    itemArray[0],
                    itemArray[1],
                    DateTools.stringToDate(itemArray[2].trim()),
                    itemArray[3]};
            batch.add(values);
        }
        jdbcTemplate.batchUpdate("insert into item (item_no, name, last_date, state) values (?,?,?,?)",batch);*/
        itemRepository.saveAll(itemList);
        model.addAttribute("message","导入成功");

        return "item/import";
    }
}
